<template>
  <div class="cc-admin row">


    <q-form @submit="submitTicketconfig"   class="dialog_card column">

      <div class="row no-wrap full-width">
        <div class="q-gutter-xs q-col-gutter-x-md" style="padding-left: 30px;margin-top: 20px;">
          <q-btn icon="mdi-restore" no-wrap color="red" label="生成红包" @click="do_make()" />
        </div>
      </div>
      <q-scroll-area class="col">
          <div class="row q-col-gutter-x-md dialog_form q-pa-md">
            <div class="col-lg-5">
              <h5>系统发放总量:</h5>
              <q-input outlined dense v-model="ticketconfigfrm.total_value"    type="number"  />
            </div>
            <div class="col-lg-5">
              <h5>红包（优惠券）名称</h5> <q-input outlined dense v-model="ticketconfigfrm.name" type="text" />
            </div>

            <div class="col-lg-5">
              <h5>红包（优惠券）使用时间: {{ticketconfigfrm.start_time}} 至 {{ticketconfigfrm.end_time}}</h5>
              <q-input outlined dense v-model="ticketconfigfrm.start_time"    style="margin-top: 20px;width:300px;"    >
                <q-btn icon="event" round color="primary">
                  <q-popup-proxy  cover transition-show="scale" transition-hide="scale">
                    <q-date v-model="proxyDate"  mask="YYYY-MM-DD HH:mm:ss">
                      <div class="row items-center justify-end q-gutter-sm">
                        <q-btn label="确认" color="primary" flat @click="saveStartTime" v-close-popup />
                        <q-btn label="取消" color="primary" flat v-close-popup />
                      </div>
                    </q-date>
                  </q-popup-proxy>
                </q-btn>
              </q-input>
              <q-input outlined dense v-model="ticketconfigfrm.end_time"       style="margin-top: 20px;width:300px;" >
                <q-btn icon="event" round color="primary">
                  <q-popup-proxy  cover transition-show="scale" transition-hide="scale">
                    <q-date v-model="proxyEndDate"  mask="YYYY-MM-DD HH:mm:ss">
                      <div class="row items-center justify-end q-gutter-sm">
                        <q-btn label="确认" color="primary" flat @click="saveEndTime" v-close-popup />
                        <q-btn label="取消" color="primary" flat v-close-popup />
                      </div>
                    </q-date>
                  </q-popup-proxy>
                </q-btn>
              </q-input>
            </div>

            <div class="col-lg-5">
              <h5>本批次红包的总额最小值:</h5>
              <q-input outlined dense v-model="ticketconfigfrm.limit_sum_min" type="text"  />
            </div>
            <div class="col-lg-5">
              <h5>本批次红包的总额:</h5>
              <q-input outlined dense v-model="ticketconfigfrm.limit_sum_max" type="text"  />
            </div>
            <!--<div class="col-lg-5">
              <h5>商户ID:</h5>
              <q-input outlined dense v-model="ticketconfigfrm.seller_id"    type="number"  />
            </div>-->

            <div class="col-lg-5">
              <h5>优惠券类型:</h5>
              <q-select outlined dense map-options v-model="ticketconfigfrm.type" :options="typej2"
              @input="onTypeValueChange" ></q-select>
            </div>

            <!--<div class="col-lg-5">
              <h5>条件值:</h5>
              <q-input outlined dense v-model="ticketconfigfrm.condition"     />
            </div>

            <div class="col-lg-5">
              <h5>用户ID:</h5>
              <q-input outlined dense v-model="ticketconfigfrm.user_id"   type="number"   />
            </div>-->

            <div class="col-11">
              <h5>红包简介:</h5>
              <div >
                  <q-input outlined dense v-model="ticketconfigfrm.intro" filled outlined autogrow    />
              </div>
            </div>

            <div class="col-lg-5">
              <h5>单个红包最小值:</h5>
              <div >
                  <q-input outlined dense v-model="ticketconfigfrm.min_value" @input="handinput" />比如 0.50，或是百分比 5%。
              </div>
            </div>
            <div class="col-lg-5">
              <h5>单个红包最大值:</h5>
              <div >
                <q-input outlined dense  v-model="ticketconfigfrm.max_value" @input="handinput" />比如 10.50，或是百分比 10%
              </div>
            </div>
            <div class="col-lg-5">
              <h5>红包批次数量:</h5>
              <div >
                <q-input outlined dense  v-model="ticketconfigfrm.ticket_num" type="number"  />
              </div>
            </div>
            <div class="col-lg-5">
              <h5>红包批次持续分钟数:</h5>
              <div >
                <q-input outlined dense  v-model="ticketconfigfrm.ticket_duration" type="text"  />
              </div>
            </div>
            <div class="col-lg-5">
              <h5>批次间隔分钟数:</h5>
              <div >
                <q-input outlined dense  v-model="ticketconfigfrm.interval_minute" type="number"  />
              </div>
            </div>
            <div class="col-lg-5">
              <h5>下一批增加的金额:</h5>
              <div >
                <q-input outlined dense  v-model="ticketconfigfrm.ticket_value_add" type="text"  />
              </div>
            </div>
            <div class="col-lg-5">
              <h5>本批次红包可领取用户数量:</h5>
              <div >
                <q-input outlined dense  v-model="ticketconfigfrm.limit_num" type="number"  />
              </div>
            </div>
          </div>
      </q-scroll-area>

       <div class="row justify-center q-pa-md">
        <q-btn class="q-mx-sm" color="primary" icon="mdi-check-bold" label="提交" type="submit" />
        <q-btn outline color="primary" icon="mdi-close-thick" label="关闭" v-close-popup />

      </div>

      </q-form>

</div>
</template>
<!-- --优惠券列表------------------------ -->
<script>
import { IndexMixin } from 'boot/mixins';
import { getDictLabel } from 'boot/dictionary';
import confirm from 'components/confirm';
import { requiredTest } from 'boot/inputTest';
import catalogselect from 'components/catalogselect';
import viewcatalog from 'components/viewcatalog';
import { ref } from 'vue'
import { date } from 'quasar'
const timeStamp = Date.now()
const formattedString = date.formatDate(timeStamp, 'YYYY-MM-DD')
const date_show = ref('2019-03-01')

export default {
  name: 'MntDeploy',
  mixins: [IndexMixin],
  components: {
    confirm,
    catalogselect,

  },
  data() {
    return {
      date_show: '2023-08-23',
      proxyDate: '2023-08-23',
      proxyEndDate:'',
      description:'',
      typej: {0:"全品类",1:"只用于某个商品",2:"只用某分类",3:"固定红包",4:"随机红包",5:"微信红包"},
      typej2: [{value: '0', label: '全品类'},{value: '1', label: '只用于某个商品'},{value: '2', label: '只用某分类'},{value: '3', label: '固定红包'},{value: '4', label: '随机红包'},{value: '5', label: '微信红包'}],
      typeArr: [],
      ticketTypeArr: [],
      form: {
        total_value: '', // 系统发放总量
        name: '',  // 本批次红包的名称
        type: '',  // 本批次红包的类型
        intro: '',       // 简介
        limit_sum_min: '', // 本批次红包的总额最小值
        limit_sum_max: '', // 本批次红包的总额最大值
        start_time: '', // 开始时间
        end_time:'', // 结束时间
        min_value: '', // 单个红包最小值
        max_value: '', // 单个红包最大值
        ticket_num: '', // 红包批次数量
        interval_minute: '', // 批次间隔分钟数
        limit_num: '', // 本批次红包可领取用户数量
        ticket_value_add: '', // 下一批增加的金额
        ticket_duration: ''  // 红包批次持续分钟数
      },
      columns: [
        { name: 'id', align: 'center', label: '序号', field: 'id', },
        {
          name: 'name', align: 'left', label: '名称', field: 'name',
        },
        {
          name: 'value', align: 'right', label: '值', field: 'value',
        },
        {
          name: 'start_time', align: 'center', label: '开始时间', field: 'start_time',
        },
        {
          name: 'end_time', align: 'center', label: '结束时间', field: 'end_time',
        },
        {
          name: 'seller_id', align: 'right', label: '商户ID', field: 'seller_id',
        },
        {
          name: 'point', align: 'center', label: '需要兑换的积分数', field: 'point',
        },

        {
          name: 'type', align: 'center', label: '类型', field: 'type',
        },

        {
          name: 'condition', align: 'center', label: '条件值', field: 'condition',
        },

        {
          name: 'limit_sum', align: 'center', label: '发券数量', field: 'limit_sum',
        },
        {
          name: 'intro', align: 'center', label: '简介', field: 'intro',
        },
        {
          name: 'img', align: 'center', label: '封面图', field: 'img',
        },
		    {
          name: 'min_value', align: 'center', label: '最小值', field: 'min_value',
        },
        {
          name: 'user_id', align: 'center', label: '用户', field: 'user_id',
        },
        {
          name: 'total_num', align: 'center', label: '发放红包总数', field: 'total_num',
        },

        {
          name: 'opt', align: 'center', label: '操作', field: 'id',
        }
      ],
      showQuery: true,
      headers: [{ name: 'Authorization', value: localStorage.Authorization }],
      uploadUrl: `${process.env.BASE_URL}/uploadfile`,
      imgUrl: `http://img.tel.gzzsu.com`,
      url: {
        list: '/ticketlist',
        add: '/ticketadd',
        detail: '/ticketgetconfig',
      },
      isEdit: 0,
      modelList: [],
      user_id:null,
      ticketconfig_dialog:true,
      ticketconfigfrm:{
        total_value: '', // 系统发放总量
        name: '',  // 本批次红包的名称
        type: '',  // 本批次红包的类型
        intro: '',       // 简介
        limit_sum_min: '', // 本批次红包的总额最小值
        limit_sum_max: '', // 本批次红包的总额最大值
        start_time: '', // 开始时间
        end_time:'', // 结束时间
        min_value: '', // 单个红包最小值
        max_value: '', // 单个红包最大值
        ticket_num: '', // 红包批次数量
        interval_minute: '', // 批次间隔分钟数
        limit_num: '', // 本批次红包可领取用户数量
        ticket_value_add: '', // 下一批增加的金额
        ticket_duration: ''  // 红包批次持续分钟数
      },
    };
  },
  methods: {
    do_make () {
      this.$router.push(
        {path: '/ticket/ticketautomake'}
      )
    },
    handinput (e){
      const p = e.replace(/[^0-9.]/g,'')
      this.ticketconfigfrm.min_value = Math.round(p * 100) / 100
    },
    getTicketConfig(){
      this.$axios.post(this.url.detail, {}).then((r) => {
        if(r.code == 0) {
          this.ticketconfigfrm.total_value = r.data.total_value
          this.ticketconfigfrm.name = r.data.name
          // this.ticketconfigfrm.type = r.data.type  //下面特殊处理
          this.ticketconfigfrm.intro = r.data.intro
          this.ticketconfigfrm.limit_sum_min = r.data.limit_sum_min
          this.ticketconfigfrm.limit_sum_max = r.data.limit_sum_max
          this.ticketconfigfrm.start_time = r.data.start_time
          this.ticketconfigfrm.end_time = r.data.end_time
          this.ticketconfigfrm.min_value = r.data.min_value
          this.ticketconfigfrm.max_value = r.data.max_value
          this.ticketconfigfrm.ticket_num = r.data.ticket_num
          this.ticketconfigfrm.interval_minute = r.data.interval_minute
          this.ticketconfigfrm.limit_num = r.data.limit_num
          this.ticketconfigfrm.ticket_value_add = r.data.ticket_value_add
          this.ticketconfigfrm.ticket_duration = r.data.ticket_duration
          for(const i in this.typej2){
            console.log(r.data.type)
            if(r.data.type && r.data.type == parseInt( this.typej2[i].value )){
              this.ticketconfigfrm.type = this.typej2[i]
            }
          }
        }

        console.log(this.ticketconfigfrm)
        // this.ticketconfigfrm = r.data
      });
    },
    updateProxy () {
      this.ticketconfigfrm.start_time = this.proxyDate
    },

    saveStartTime() {
      this.ticketconfigfrm.start_time = this.proxyDate
    },
    saveEndTime(){
      this.ticketconfigfrm.end_time = this.proxyEndDate
    },
    onValueChange(val) {
      console.log("447 >>>>>>>",val);

    },
    refresh(){

    },
    detail(id) {
      this.$axios.post(this.url.detail, {id:  id}).then(
          (r) => {
            console.log(r.data)
            this.form = r.data
            this.dialogdetialVisible = true;
          }
        );
    },
    requiredTest,
    addBefore() {
      this.form.catalogId = this.catalog;
      return true;
    },
    selectCatalog(n) {
      this.catalog = n;
      this.query();
    },
    selectFiles() {
      this.$refs.fileUploader.pickFiles();
    },
    importAvatar() {
      this.$refs.avatarUploader.pickFiles();
    },
    importedAvatar({ xhr }) {
      const response = JSON.parse(xhr.responseText);
      if (response.code == 0) {
        this.form.img = response.data.url
        console.log(this.form.ad_img)
        this.$q.notify('上传成功');
      } else {
        this.$q.notify({
          color: 'red',
          message: '上传失败',
        });
      }
      this.$refs.avatarUploader.removeUploadedFiles();
    },
    uploadedFiles({ xhr }) {
      const response = JSON.parse(xhr.responseText);
      if (response.success) {
        this.$q.notify('上传成功');
        this.queryImages();
      } else {
        this.$q.notify({
          color: 'red',
          message: '上传失败',
        });
      }
      this.$refs.fileUploader.removeUploadedFiles();
    },
    imagePath(src) {
      let path = '';
      if (src) {
        if (src.startsWith('http')) {
          return src;
        }
        path = `${this.imgUrl}/${src}`;
      }
      return path;
    },
    queryImages() {
      // this.$axios.get(`/sys/file/listByMainId?mainId=${this.form.id}`).then(({ result }) => {
      //   this.attachments = result;
      // });
    },
    getGoodsLabel(status){
      const list = {
        menuType: [0 , 1, 2 ],
        icon: ['正常', '删除' ],
      };
      const showStatus = ['正常', '删除' ];
      return showStatus[status]
    },
    typetran(val) {
      return this.typej[val];
    },
    initDict() {
      this.getTicketConfig()
    },
    deploy() {
      this.$refs.keyFileUploader.pickFiles();
    },
    importedDeploy({ xhr }) {
      this.$refs.keyFileUploader.removeUploadedFiles();
      const { response } = xhr;
      const res = JSON.parse(response);
      if (res.success) {
        this.form.keyFile = res.message;
      } else {
        this.$error(res.message);
      }
    },
    sysRestore() {
      this.$refs.sysRestore.dialog = true;
    },
    onSubmit (evt) {
      let url = ''
      if (this.form.start_time < this.form.end_time  ) {
        return this.$q.notify({
          color: 'red',
          message: '起始时间必须大于截止时间!',
        });
      }

      if(this.form.store_nums < 0){
        this.$q.notify({
          color: 'red',
          message: '商品库存不能小于0',
        });
        return
      }else{
        if(this.isEdit == 1){
          url = this.url.edit
        }else{
          url = this.url.add
        }
        this.$axios.post(url,this.form).then((r) => {
          this.babyWord = r;
          if(r.success = true){
            this.$q.notify({ position: 'top', color: 'info', textColor: 'white', icon: 'cloud_done', group: false, html: true, message: '保存成功！！',});
            this.onReset()
            this.refresh()

          }else{
            this.$q.notify({ position: 'top', color: 'error', textColor: 'red', icon: 'cloud_done', group: false, html: true, message: r.msg,});
          }
        });
      }

      //evt.target.submit()
    },
    onReset(){
      this.form = {
        total_value: '', // 系统发放总量
        name: '',  // 本批次红包的名称
        type: '',  // 本批次红包的类型
        intro: '',       // 简介
        limit_sum_min: '', // 本批次红包的总额最小值
        limit_sum_max: '', // 本批次红包的总额最大值
        start_time: '', // 开始时间
        end_time:'', // 结束时间
        min_value: '', // 单个红包最小值
        max_value: '', // 单个红包最大值
        ticket_num: '', // 红包批次数量
        interval_minute: '', // 批次间隔分钟数
        limit_num: '', // 本批次红包可领取用户数量
        ticket_value_add: '', // 下一批增加的金额
        ticket_duration: ''  // 红包批次持续分钟数
      }
    },
    queryParam() {
      //组合查询参数
      const data={};
      if (this.user_id >0) {
        data['user_id'] = this.user_id;
      }
      this.searchForm = data;
    },
    onTypeValueChange(val) {
      const _type = val.value;
      //如果是随机红包type=4，则取值是在 min_value 到 value之间的一个随机数额。
      if (_type == 4) {
        const min=this.ticketconfigfrm.min_value  ;
        const max = this.ticketconfigfrm.value==0?1:this.ticketconfigfrm.value;
        const _value = Math.floor(Math.random() * (max - min + 1) + min);
        this.$set(this.ticketconfigfrm, 'value', _value);
      }
    },
    submitTicketconfig() {
      if(this.ticketconfigfrm.min_value < 0.05){
        this.$q.notify({
          color: 'red',
          message: '最小值不能小于0.05',
        });
        return
      }
      // console.log(this.ticketconfigfrm.min_value)
      // return
      this.ticketconfigfrm.type = this.ticketconfigfrm.type.value
      this.$axios.post('/ticketsetconfig',this.ticketconfigfrm).then((r) => {
        if (r.code == 0) {
          this.$q.notify('保存成功');
        }else{
          this.$q.notify({ position: 'center', color: 'red', textColor: 'white', icon: 'cloud_done', html: true, message: r.msg});
        }
      });
    }
  },
  mounted() {
    this.initDict();
    this.typeArr = Object.values(this.typej)
    this.form.start_time = new Date().toLocaleDateString().split('/').join('-');
    this.form.end_time = new Date().toLocaleDateString().split('/').join('-');
  },
};
</script>

<style lang="stylus"></style>
